package bma.common.netty.protobuf.core;

import bma.common.langutil.core.ValueUtil;
import bma.common.netty.protobuf.core.BaseProtos.PError;

public class PErrorException extends RuntimeException {

	private int code = 500;
	private String type;

	public PErrorException() {
		super();
	}

	public PErrorException(String message, Throwable cause) {
		super(message, cause);
	}

	public PErrorException(String message) {
		super(message);
	}

	public PErrorException(Throwable cause) {
		super(cause);
	}

	public PErrorException(int code, String type, String msg) {
		super(msg);
		this.code = code;
		this.type = type;
	}

	public String getType() {
		return type == null ? getClass().getName() : type;
	}

	public int getCode() {
		return code;
	}

	public static PErrorException create(PError err) {
		Throwable t = null;
		String msg = err.getMessage();
		if (err.hasInnerError()) {
			PError ie = err.getInnerError();
			if (ie != null) {
				t = create(ie);
			}
		}
		PErrorException r = new PErrorException(msg, t);
		r.type = err.getType();
		r.code = err.getCode();
		return r;
	}

	public PError toError() {
		PError.Builder b = PError.newBuilder();
		b.setCode(code);
		b.setType(ValueUtil.empty(type) ? "exception" : type);
		b.setMessage(getMessage());
		return b.build();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(200);
		sb.append(getClass().getName()).append(":");
		sb.append("[").append(code);
		if (!ValueUtil.empty(type)) {
			sb.append("|").append(type);
		}
		sb.append("] ").append(getMessage());
		return sb.toString();
	}
}
